package hot100;

public class mergeTwoLists2 {
    public mergeKLists.ListNode mergeTwoLists(mergeKLists.ListNode list1, mergeKLists.ListNode list2) {
        if(list1 == null) {
            return list2;
        }
        if(list2 == null) {
            return list1;
        }
        mergeKLists.ListNode ret = new mergeKLists.ListNode(0);
        mergeKLists.ListNode cur = ret;

        //保证 第一个结点是小的是list1
        if(list1.val >= list2.val) {
            mergeKLists.ListNode temp = list1;
            list1 = list2;
            list2 = temp;
        }
        while(list1 != null && list2 != null) {
            if(list1.val < list2.val) {
                ret.next = list1;
                list1 = list1.next;
            }else {
                ret.next = list2;
                list2 = list2.next;
            }
            ret = ret.next;
        }
        if(list1 == null) {
            while(list2 != null) {
                ret.next = list2;
                list2 = list2.next;
                ret = ret.next;
            }
        }else {
            while(list1 != null) {
                ret.next = list1;
                list1 = list1.next;
                ret = ret.next;
            }
        }
        return cur.next;


    }
}
